<template>
  <div>
    <el-dialog :title="title"
               :visible.sync="visible"
               v-loading="loading"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="90%">
      <el-form :model="formModel"
               label-position="right"
               ref="formModelRef"
               label-width="100px"
               :rules='formModelRules'>
        <el-form-item label="厂家名称："
                      prop="factoryDto.name">
          <el-input placeholder="请输入厂家名称"
                    maxlength="20"
                    show-word-limit
                    v-model="formModel.factoryDto.name"
                    clearable
                    class="w-200"></el-input>
        </el-form-item>

        <el-form-item label="联系人："
                      prop="factoryDto.contacts">
          <el-input placeholder="请输入联系人"
                    v-model="formModel.factoryDto.contacts"
                    class="w-200"></el-input>
        </el-form-item>
        <el-form-item label="联系电话："
                      prop="factoryDto.phone">
          <el-input v-model="formModel.factoryDto.phone"
                    placeholder="请输入联系电话"
                    class="w-200"></el-input>
        </el-form-item>
        <el-form-item label="合作商品："
                      prop="saveSellDrugRequestDtoList">
          <el-button type="success"
                     @click="handleOption('add', null, null)">新 增 一 项</el-button>
          <el-table :data="formModel.saveSellDrugRequestDtoList"
                    class="mt-20"
                    border
                    width="100%"
                    style="width:100%">
            <el-table-column label="商品名称"
                             prop="sellDrugDto.drugName"
                             width="120"
                             align="center">
            </el-table-column>
            <el-table-column prop="sellDrugDto.drugType"
                             label="所属分类"
                             width="100"
                             align="center">
              <template slot-scope="scope">
                <el-tag type="success"
                        v-if="scope.row.sellDrugDto.drugType === 2">化学药</el-tag>
                <el-tag type="success"
                        v-if="scope.row.sellDrugDto.drugType === 3">中成药</el-tag>
                <el-tag type="success"
                        v-if="scope.row.sellDrugDto.drugType === 4">保健品</el-tag>
                <el-tag type="success"
                        v-if="scope.row.sellDrugDto.drugType === 5">器械</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sellDrugDto.logoUrl"
                             label="图片"
                             width="150"
                             align="center">
              <template slot-scope="scope">
                <el-image style="width: 100px; height: 100px"
                          :src="scope.row.sellDrugDto.logoUrl"
                          :preview-src-list="[scope.row.sellDrugDto.logoUrl]">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="sellDrugDto.standard"
                             label="规格"
                             align="center"
                             width="100">
            </el-table-column>
            <el-table-column prop="sellDrugDto.drugPackage"
                             label="包装"
                             align="center"
                             width="100">
            </el-table-column>
            <el-table-column prop="sellDrugDto.functionalIndications"
                             label="功能主治"
                             align="center">
            </el-table-column>
            <el-table-column prop="sellDrugDto.taboo"
                             label="禁忌"
                             align="center">
            </el-table-column>
            <el-table-column prop="sellDrugDto.adverseReaction"
                             label="不良反应"
                             align="center">
            </el-table-column>
            <el-table-column prop="themes"
                             label="关联主题"
                             align="center">
              <template slot-scope="scope">
                <el-tag type="success"
                        v-for="item in scope.row.sellDrugDto.themes"
                        :key="item.id"
                        style="margin-bottom: 5px; margin-right:5px">
                  {{item.name}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="address"
                             label="操作"
                             width="160"
                             align="center">
              <template slot-scope="scope">
                <el-button type="primary"
                           @click="handleOption('edit', scope.row, scope.$index)">编 辑</el-button>
                <el-button type="danger"
                           @click="handleOption('del', scope.row, scope.$index)">删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <p align="center">
        <el-button @click="modalClose"
                   type="info">取 消</el-button>
        <el-button type="primary"
                   @click="submitForm">保 存</el-button>
      </p>
      <add-shop-dialog :shopListData="shopListData"
                       :dataObj="dataObj"
                       :getDetail="getDetail"
                       @shopData="shopData"
                       v-if="isShowShop"
                       :visible.sync="isShowShop"></add-shop-dialog>
    </el-dialog>
  </div>
</template>
<script>
  import addShopDialog from './addShopDialog'
  export default {
    name: '', // 合作厂家管理
    props: {
      dataObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      },
      getList: {
        type: Function,
        default: null
      },
    },
    data () {
      const phoneValidate = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('手机号不能为空'));
        } else {
          const reg = /^1[3456789]\d{9}$/
          if (reg.test(value)) {
            callback();
          } else {
            return callback(new Error('请输入正确的手机号!'));
          }
        }
      };
      return {
        title: '新 增',
        loading: false,
        isShowShop: false,
        formModel: {
          factoryDto: {
            name: '',
            contacts: '', // 联系人
            phone: '', // 联系电话
          },
          saveSellDrugRequestDtoList: [
            /* {
              sellDrugDto: {
                drugId: null, // 药品id
                logoUrl: '', // 图片地址
                salesScript: '', // 销售话术
                functionalIndications: '', // 功能主治
                taboo: '', // 禁忌症
                adverseReaction: '', // 不良反应
                drugType: '', // 药品类型
              },
              themeIds: [],
              advertisingRequestDto: [
                {
                  title: '',
                  advertising: '',
                  logoUrl: '',
                }
              ]
            } */
          ],
        },

        formModelRules: {
          'factoryDto.name': [
            { required: true, message: '请输入厂家名称', trigger: 'blur' }
          ],
          'factoryDto.contacts': [
            { required: true, message: '请输入联系人', trigger: 'blur' }
          ],
          'factoryDto.phone': [
            { required: true, validator: phoneValidate, trigger: 'blur' }
          ],
          saveSellDrugRequestDtoList: [
            { required: true, message: '请输配置合作商品', trigger: ['blur', 'change'] }
          ],
        },
        shopListData: {},
      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },
      // 动态添加行
      handleOption (op, row, index) {
        switch (op) {
          case 'add':
            this.isShowShop = true;
            this.shopListData = null;
            break;
          case 'edit':
            this.isShowShop = true;
            if (row.sellDrugDto.sellDrugKnowledgeDtos === undefined) {
              row.sellDrugDto['sellDrugKnowledgeDtos'] = [];
            }
            this.shopListData = Object.assign({}, row);
            break;
          case 'del':
            if (row.sellDrugDto.id) {
              this.$confirm('您是否要删除当前商品？')
                .then(async _ => {
                  const { data: res } = await this.post(this.api.promote.delShop, { id: row.sellDrugDto.id })
                  if (res.code === '200') {
                    this.$message.success('删除成功!');
                    this.getDetail();
                  }
                })
                .catch(_ => { });
            } else {
              this.formModel.saveSellDrugRequestDtoList.splice(index, 1);
            }
            break;
        }
      },
      // 获取子组件传过来的数据
      shopData (data) {
        this.formModel.saveSellDrugRequestDtoList.push(data);
      },
      submitForm () {
        this.$refs.formModelRef.validate(async (valid) => {
          if (valid) {
            /*  let falg = this.formModel.saveSellDrugRequestDtoList.every(item => {
               if (item === '') {
                 return true;
               }
             });
             if (!falg) {
               this.$message.error('商品每一项属性必填!');
               return
             } */
            let result = true;
            let message = [];
            this.formModel.saveSellDrugRequestDtoList.forEach((item, index) => {
              let no = index + 1;
              if (item.sellDrugDto.logoUrl === '') {
                result = result && false;
                message.push('第' + no + '行：图片不能为空');
              }
              if (item.sellDrugDto.functionalIndications === '') {
                result = result && false;
                message.push('第' + no + '行：功能主治不能为空');
              }
              if (item.sellDrugDto.taboo === '') {
                result = result && false;
                message.push('第' + no + '行：禁忌不能为空');
              }
              if (item.sellDrugDto.adverseReaction === '') {
                result = result && false;
                message.push('第' + no + '行：不良反应不能为空');
              }
              if (this.dataObj) {
                if (item.themes.length === 0) {
                  result = result && false;
                  message.push('第' + no + '行：关联主题不能为空');
                }
              }

            });
            if (!result) {
              let temp = '';
              message.forEach(item => {
                temp += `<li>${item}</li>`;
              });
              return this.$notify({
                title: '商品属性列表提示',
                dangerouslyUseHTMLString: true,
                type: 'warning',
                duration: 3000,
                message: `<ul>${temp}</ul>`
              });
            }
            if (this.dataObj) { // 编辑
              delete this.formModel.saveSellDrugRequestDtoList;
              delete this.formModel.sellDrugInfoResponseList;
              const { data: res } = await this.post(this.api.promote.updateFactory, { ...this.formModel.factoryDto });
              if (res.code === '200') {
                this.modalClose();
                this.$parent.getList() // 调用父件组方法
                this.$message.success('保存成功!');
              }
            } else { // 新增
              if (this.formModel.saveSellDrugRequestDtoList.length === 0) {
                this.$message.error('请配置合作商品!');
                return
              }
              const { data: res } = await this.post(this.api.promote.saveFactory, this.formModel);
              if (res.code === '200') {
                this.modalClose();
                this.$parent.getList() // 调用父件组方法
                this.$message.success('保存成功!');
              }
            }

          }
        })
      },

      // 查询详情
      async getDetail () {
        const { data: res } = await this.post(this.api.promote.getFactory, {
          id: this.dataObj.id
        });
        if (res.code === '200') {
          let resData = res.object;
          this.formModel.factoryDto = resData.factoryDto;
          resData.sellDrugInfoResponseList.forEach(item => {
            item.sellDrugDto['themes'] = item.themes;
            if (item.sellDrugDto.sellDrugKnowledgeDtos === undefined) {
              item.sellDrugDto['sellDrugKnowledgeDtos'] = [];
            }
          });
          this.formModel.saveSellDrugRequestDtoList = resData.sellDrugInfoResponseList;
        }

      }
    },
    created () {
      if (this.dataObj) {
        this.getDetail() // 查询详情
        this.title = '编 辑'
      }

    },
    components: {
      'add-shop-dialog': addShopDialog
    }
  }
</script>
<style scoped lang="scss">
</style>